package ae.pcfc.etks.online.web.controller.admin.general.user;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import ae.pcfc.etks.online.common.ConstantsCommon;
import ae.pcfc.etks.online.common.delegate.SecretQuestionDelegate;
import ae.pcfc.etks.online.common.delegate.ServiceDelegate;
import ae.pcfc.etks.online.common.delegate.UserDelegate;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.SecretQuestionVO;
import ae.pcfc.etks.online.common.vo.ServiceRoleVO;
import ae.pcfc.etks.online.common.vo.UserVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.PageType;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.common.Constants;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.InternalStaff;
import ae.pcfc.etks.online.web.model.Service;
import ae.pcfc.etks.online.web.util.SecurityUtils;

/* $Id: AdminInternalStaffController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * Jan 4, 2012 	Ismail 	        Created
 *
 */

/**
 * Controller that handles all {@link AdminInternalStaffController}-related
 * requests, i.e.: all requests for /admin/general/user/internal* Manages
 * internal user creation and editing
 * 
 * @author Ismail
 */

@Controller
@RequestMapping(ViewPath.ADMIN_GENERAL_USER_INTERNAL)
public class AdminInternalStaffController extends BaseController {

	private Validator validator;

	// message resource
	private ResourceBundleMessageSource messageSource;

	@Resource(name = "messageSource")
	public void setMessageSource(ResourceBundleMessageSource messageSource) {
		this.messageSource = messageSource;
	}

	@Resource(name = "validator")
	public void setValidator(Validator validator) {
		this.validator = validator;
	}

	private UserDelegate userDelegate;

	@Resource(name = "userDelegate")
	public void setUserDelegate(UserDelegate userDelegate) {
		this.userDelegate = userDelegate;
	}

	private SecretQuestionDelegate secretQuestionDelegate;

	@Resource(name = "secretQuestionDelegate")
	public void setSecretQuestionDelegate(
			SecretQuestionDelegate secretQuestionDelegate) {
		this.secretQuestionDelegate = secretQuestionDelegate;
	}

	private ServiceDelegate serviceDelegate;

	@Resource(name = "serviceDelegate")
	public void setServiceDelegate(ServiceDelegate serviceDelegate) {
		this.serviceDelegate = serviceDelegate;

	}

	@InitBinder
	public void initBinder(WebDataBinder binder, Locale locale) {
		binder.setValidator(validator);
	}

	@ModelAttribute(ConstantsAdmin.USER_SECRETQUESTION_REQUEST_MODEL_KEY)
	public List<LabelVO> populateSecretQuestionList() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO;
		List<SecretQuestionVO> secretQuestionVOs = secretQuestionDelegate
				.getSecretQuestionList();

		for (SecretQuestionVO secretQuestionVO : secretQuestionVOs) {
			labelVO = getMapper().map(secretQuestionVO, LabelVO.class);
			labelList.add(labelVO);

		}
		return labelList;
	}

	@ModelAttribute(ConstantsAdmin.USER_ADMIN_INTERNAL_STAFF_ROLES_MODEL_KEY)
	public List<LabelVO> populateInternalStaffRoleList(Locale locale) {
		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO;
		List<ServiceRoleVO> internalStaffRolesList = serviceDelegate
				.findServiceRolesByServiceType(ConstantsCommon.SERVICE_INTERNAL);
		if (internalStaffRolesList != null) {
			for (ServiceRoleVO serviceRoleVO : internalStaffRolesList) {
				labelVO = getMapper().map(serviceRoleVO, LabelVO.class);
				labelList.add(labelVO);

			}
		}
		return labelList;
	}

	@ModelAttribute(ConstantsAdmin.USER_ADMIN_USER_LOCK_MODEL_KEY)
	public List<LabelVO> populateActionList(Locale locale) {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();
		labelVO.setId(Constants.ACTIVE);

		labelVO.setDisplayLabel(messageSource.getMessage("label.user.active",
				null, locale));

		labelList.add(labelVO);

		labelVO = new LabelVO();
		labelVO.setId(Constants.INACTIVE);
		labelVO.setDisplayLabel(messageSource.getMessage("label.user.inactive",
				null, locale));

		labelList.add(labelVO);

		return labelList;
	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * admin/general/user/internal/form.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/user/internal/form.jsp
	 */

	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void add(
			@ModelAttribute(ConstantsAdmin.ADMIN_INTERNAL_STAFF_INFO) InternalStaff model) {
		model.setStrStatus("A");
	}

	/**
	 * Custom handler for displaying the form, i.e.: POST requests for
	 * admin/general/user/internal/form.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/user/internal/form.jsp
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public String form(
			HttpServletRequest request,
			HttpSession session,
			SessionStatus status,
			Model model,
			Locale locale,
			@ModelAttribute(ConstantsAdmin.ADMIN_INTERNAL_STAFF_INFO) InternalStaff internalStaff,
			BindingResult errors) throws Exception {

		UserVO userVO = new UserVO();
		getMapper().map(internalStaff, userVO);

		userVO.setCreateDate(Calendar.getInstance().getTime());
		userVO.setStrType(ConstantsCommon.INTERNAL_TRAKHEES_STAFF);

		userVO.setStrPassword(SecurityUtils.hashPassword(userVO
				.getStrPassword()));
		serviceDelegate.registerInternalStaff(userVO,
				internalStaff.getArrRoles());
		session.setAttribute(ConstantsAdmin.SUCCESS_PARAM, messageSource
				.getMessage("success.user.info.edit", null, locale));
		status.setComplete();
		return ViewUtils
				.getRedirect(ViewPath.ADMIN_GENERAL_USER, PageType.LIST);

	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * admin/general/user/internal/form/edit.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/user/internal/edit.jsp
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public void edit(
			HttpServletRequest request,
			Model model,
			@RequestParam(value = "userId", required = true) String userId,
			@ModelAttribute(ConstantsAdmin.ADMIN_INTERNAL_STAFF_INFO) InternalStaff internalStaff,
			Locale locale) {

		UserVO userVO = this.userDelegate.findUserByPrimaryKey(Long
				.valueOf(userId));

		if (userVO != null) {
			getMapper().map(userVO, internalStaff);
			List<ServiceRoleVO> serviceRoleVOList = this.serviceDelegate
					.findServiceRolesByUserName(internalStaff.getStrUserName());
			List<Long> listSrRoleIds = new ArrayList<Long>();
			if (serviceRoleVOList != null) {
				for (ServiceRoleVO serviceRoleVO : serviceRoleVOList) {
					listSrRoleIds.add(serviceRoleVO.getSrId());
				}
			}

			internalStaff.setArrRoles(listSrRoleIds);
		}
	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * admin/general/user/internal/edit.jsp
	 * 
	 * @see #form(Service)
	 * @see WEB-INF/jsp/admin/general/user/internal/edit.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/edit.htm")
	public String edit(
			HttpServletRequest request,
			Model model,
			HttpSession session,
			SessionStatus status,
			Locale locale,
			@ModelAttribute(value = ConstantsAdmin.ADMIN_INTERNAL_STAFF_INFO) InternalStaff internalStaff,
			BindingResult errors) {

		UserVO userVO = null;
		userVO = userDelegate
				.findUserByUserName(internalStaff.getStrUserName());
		if (userVO == null) {
			return ViewUtils.DEFAULT_VIEW;
		}
		getMapper().map(internalStaff, userVO);
		if (internalStaff.getStrEmailNotification() == null) {
			userVO.setStrEmailNotification(null);
		}
		if (internalStaff.getStrMobileNotification() == null) {
			userVO.setStrSmsNotification(null);
		}

		userVO.setCreateDate(Calendar.getInstance().getTime());
		userVO.setStrType(ConstantsCommon.INTERNAL_TRAKHEES_STAFF);

		userVO.setStrPassword(SecurityUtils.hashPassword(userVO
				.getStrPassword()));
		serviceDelegate
				.updateInternalStaff(userVO, internalStaff.getArrRoles());
		session.setAttribute(ConstantsAdmin.SUCCESS_PARAM, messageSource
				.getMessage("success.user.info.edit", null, locale));
		status.setComplete();
		return ViewUtils
				.getRedirect(ViewPath.ADMIN_GENERAL_USER, PageType.LIST);
	}

}
